package org.argeproje.resim.ui.parts;

import java.util.ArrayList;
import java.util.Iterator;

import org.argeproje.resim.ui.model.ComponentItem;
import org.argeproje.resim.ui.model.Connection;
import org.eclipse.draw2d.ChopboxAnchor;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Point;


public class InOutAnchor extends ChopboxAnchor {
  protected transient ComponentItem _ci;
  protected boolean _isSourceAnchor;
  protected boolean _isConnected;
  protected int _pinIndex = 0;
  private Point _mouseLocation;
  public InOutAnchor(IFigure fig, ComponentItem ci, boolean isSourceAnchor, boolean isConnected){
	  super(fig);
	  _ci = ci;
	  _isSourceAnchor = isSourceAnchor;
	  setConnected(isConnected);
  }
  public void setPinIndex(int pinIndex){
	  _pinIndex = pinIndex;
  }
  public void setConnected(boolean isConnected){
	  _isConnected = isConnected;
  }
  public boolean getConnected(){
	  return _isConnected;
  }
  public Point getLocation(Point refPoint){
	Point p = null;
	ArrayList<Point> points;
	if(_isSourceAnchor){
		points = _ci.getIconFigure().getOutLocations();
		if(getConnected()){
          p = _ci.getIconFigure().getOutLocations().get(_pinIndex);
		}else{
		  p = getMinDistance(points, getMouseLocation());
		  
		}
	}else{
		if(_ci.getIconFigure().getValidInputIndices().size() == 0)
		   points = _ci.getIconFigure().getInLocations();
		else
		   points = _ci.getIconFigure().getValidInLocations();
		if(getConnected()){
		  p = _ci.getIconFigure().getInLocations().get(_pinIndex);
		}else{
		  p = getMinDistance(points, getMouseLocation());
		}
	}
	return p;  
  }
  protected Point getMinDistance(ArrayList<Point> points, Point p){
	  Point result = null;
	  if (points.size() < 1) {
			return p;
	  }
	  Iterator<Point> iterator = points.iterator();	
	  result = (Point) iterator.next();
	  double minDistance = result.getDistance(p);
	  int i = 1;
	  for (; iterator.hasNext();) {
		Point point = (Point) iterator.next();			
		double tempDistance = point.getDistance(p);
		
		if(tempDistance < minDistance){
			result = point;
			minDistance = tempDistance;
		}
		i++;
	 }
     if(_isSourceAnchor){
	    Connection.CANDIDATE_SRC_INDEX = _ci.getIconFigure().getOutLocations().indexOf(result);
	 }else{
	    Connection.CANDIDATE_DST_INDEX = _ci.getIconFigure().getInLocations().indexOf(result);
	 }
	 return result;
  }
  
  public void setMouseLocation(Point pt) {
	_mouseLocation = pt;	
  }
  public Point getMouseLocation(){
	  return _mouseLocation;
  }
}
